#include <iostream>
#include "contact.pb.h"
#include <string>
#include <fstream>

std::string file_name = "./contacts.txt";

void ReadAllPeopleInfo(Contact::ContactsInfo& contacts)
{
    for(int i = 0; i < contacts.people_size(); i++)
    {
        // 获取联系人对应下标的信息
        const Contact::PeopleInfo& people = contacts.people(i); 
        std::cout << "----------联系人" << i + 1 << "------------" << "\n";
        std::cout << "联系人名字: " << people.name() << "\n";
        std::cout << "联系人年龄: " << people.age() << "\n";
        for(int j = 0; j < people.phone_size(); j++)
        {
            const Contact::PeopleInfo_Phone& phone = people.phone(j);
            // PhoneType_Name 函数可以帮我们把枚举类型转化为它所对应的名字
            std::cout << "联系人电话" << j + 1 << ": " << phone.phone() << "    " << phone.PhoneType_Name(phone.type()) << "\n";
        }
        Contact::Address addr;
        // 这里把any中的数据转化为Address类型的数据拿出来
        if(people.has_address() && people.address().Is<Contact::Address>())
        {
            // 这里代表any中有数据 并且这个any的类型是Address
            people.address().UnpackTo(&addr);
            if(!addr.home_addr().empty())
                std::cout << "联系人家庭地址: " << addr.home_addr() << "\n";
            if(!addr.work_addr().empty())
                std::cout << "联系人工作地址: " << addr.work_addr() << "\n";
        }
        // 读取oneof字段的信息
        switch(people.contactWay_case())
        {
            case Contact::PeopleInfo::ContactWayCase::kQq : 
                std::cout << "qq :  " << people.qq() << "\n";
                break;
            case Contact::PeopleInfo::ContactWayCase::kWx : 
                std::cout << "微信 :  " << people.wx() << "\n";
                break;
        }

        std::cout << "备注信息: " << "\n";
        // 读取备注信息
        for(auto it = people.info().cbegin(); it != people.info().cend(); it++)
        {
            std::cout << it->first << "  :  " << it->second << "\n";
        }
    }
}

int main()
{
    Contact::ContactsInfo contacts;
    std::fstream input(file_name, std::ios::in | std::ios::binary);
    if(!input.is_open())
    {
        std::cout << "文件读取失败" << "\n";
        input.close();
        return -1;
    }

    // 对数据进行反序列化出来
    contacts.ParseFromIstream(&input);

    ReadAllPeopleInfo(contacts);

    input.close();
    return 0;
}